(function () {
	var alt = false,
		shift = false;

	//	Init Page Action
	chrome.extension.sendRequest({
		"action": "init",
		"host": document.location.host,
		"renderMode": document.compatMode,
		"useCache": true
	});

	chrome.extension.onRequest.addListener(function (request, sender, sendResponse) {
		if (request["type"] === "validate") {
			validateDocument();
		}
	});

	//	Set up keyboard shortcuts (Alt + Shift + V)
	document.addEventListener("keydown", function (e) {
		if (e.which === 16) {
			shift = true;
		}
		else if (e.which === 18) {
			alt = true;
		}
		else if (e.which === 86) {
			if (alt && shift) {
				validateDocument();
			}
		}
	}, false);

	document.addEventListener("keyup", function (e) {
		if (e.which === 16) {
			shift = false;
		}
		else if (e.which === 18) {
			alt = false;
		}
	});

	chrome.extension.onRequest.addListener(function (results, sender, response) {
		var i,
			count,
			line,
			message;

		//	eval() prevents extension's URI appearing in console.
		count = parseInt(results["count"]);
		if (count) {
		eval('console.group(count + " Validation Errors");');
			for(i in results["messages"]) {
				line = results["messages"][i].lastLine;
				message = results["messages"][i].message;
				switch(results["messages"][i].type) {
					case "error":
						eval("console.error('Line ' + line + ': ' + message);");
						break;
					case "warning":
						eval("console.warn('Line ' + line + ': ' + message);");
						break;
					default:
						eval("console.info('Line ' + line + ': ' + message);");
				}
			//console.log(results["messages"][i].message);
			}
		console.groupEnd();
		}
	});

	function validateDocument (useCache) {
		chrome.extension.sendRequest({
				"action":"validate",
				"host": document.location.host,
				"useCache": useCache,
				"renderMode":document.compatMode
			}/*,
			function (messages) {
				console.info(messages);
				//validity["errors"] = errorCount;
		}*/);
	}
})();